package idv.arthur.work;

import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


public class ManipulateGridHosts extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ManipulateGridHosts() {
        super();
    }
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    	doPost(request,response);
    }

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		
		Widgets wid = new Widgets();
		request.setCharacterEncoding( wid.UIcodeSet );
		response.setContentType("application/text");
		response.setCharacterEncoding( wid.UIcodeSet );
		
		Connection conn = wid.getConn(true);
		PreparedStatement ps = null;
		ResultSet rs = null;
		String errPars = "}";
		String strSQL = "";
		String oper = request.getParameter("oper");									//增刪改查那一種
		final String bssId =  request.getParameter("bssId");								//系統ID
		String subSysId = request.getParameter("subSysId");					//子系統ID
		String hostIP = request.getParameter("hostIP");							//主機IP
		int port = Integer.parseInt(request.getParameter("port"));		//PORT
		String result = "";
		final String currentUser = request.getParameter("currentUser");
		String loginId = request.getParameter("loginId");
		String loginPWD = request.getParameter("loginPWD");
		
		try {
			String hostName = wid.UI2DB( request.getParameter("hostName"),conn.getMetaData().getDatabaseProductName() );				//主機名稱
			
			/** 判別需進行何種操作 **/
			if ( "del".equalsIgnoreCase(oper) ) {
				strSQL = "DELETE FROM hosts WHERE ip=? AND subsysid=? AND bssid=? AND port=?";
				ps = conn.prepareStatement(strSQL);
				ps.setString(1, hostIP);
				ps.setString(2, subSysId);
				ps.setString(3, bssId);
				ps.setInt(4, port);
				ps.execute();
				
				wid.keepLogProfile(wid.HOST, wid.DELETE, currentUser, conn, ps);
				result = "刪除了"+hostIP;
			} else if ( "add".equalsIgnoreCase(oper) ) {
				if (! isDuplicated(bssId,subSysId,hostIP,port,conn,ps,rs) ) {
					strSQL = "INSERT INTO hosts (ip,subsysid,bssid,port,hostname,loginId,loginPWD,creator,createdDateTime) VALUES (?,?,?,?,?,?,?,?,?)";
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, hostIP);
					ps.setString(2, subSysId);
					ps.setString(3, bssId);
					ps.setInt(4, port);
					ps.setString(5, hostName);
					ps.setString(6, loginId);
					ps.setString(7, loginPWD);
					ps.setString(8, currentUser);
					ps.setTimestamp(9, wid.currentTimeStamp());
					ps.execute();
					
					wid.keepLogProfile(wid.HOST, wid.ADD, currentUser, conn, ps);
					result = "新增完成 "+hostIP;
				} else {
					result = hostIP+" 已存在 !";		
				}
			} else if ( "edit".equalsIgnoreCase(oper) ) {
				String oriBssId = request.getParameter("oriBssId");			
				String oriSubSysId = request.getParameter("oriSubSysId");
				String oriHostIP = request.getParameter("oriHostIP");
				int oriPort = Integer.parseInt(request.getParameter("oriPort"));
				
				
				/** 這四個主鍵值有一個不一樣 **/
				boolean isDifferent = (!oriBssId.equalsIgnoreCase(bssId) || !oriSubSysId.equalsIgnoreCase(subSysId) || !oriHostIP.equalsIgnoreCase(hostIP) || oriPort != port);
				
				/**	先確認要變更後的值，其主鍵並非已經存在 **/
				/**	有不一樣但沒重覆  或是  沒有不一樣 **/
				if ( (isDifferent && !isDuplicated(bssId,subSysId,hostIP,port,conn,ps,rs)) || !isDifferent) {
					strSQL = "UPDATE hosts SET ip=?,subsysid=?,bssid=?,port=?,hostname=?,lastUpdator=?,lastUpdatedDateTime=?,loginId=?,loginPWD=? WHERE ip=? AND subsysid=? AND bssid=? AND port=?";
					
					ps = conn.prepareStatement(strSQL);
					ps.setString(1, hostIP);
					ps.setString(2, subSysId);
					ps.setString(3, bssId);
					ps.setInt(4, port);
					ps.setString(5, hostName);
					ps.setString(6, currentUser);
					ps.setTimestamp(7, wid.currentTimeStamp());
					ps.setString(8, loginId);
					ps.setString(9, loginPWD);
					ps.setString(10, oriHostIP);
					ps.setString(11, oriSubSysId);
					ps.setString(12, oriBssId);
					ps.setInt(13, oriPort);
					ps.execute();
					
					wid.keepLogProfile(wid.HOST, wid.UPDATE, currentUser, conn, ps);
					result = "修改完成!! "+"\n"+"系統ID："+bssId+"\n"+"子系統ID："+subSysId+"\n"+"主機IP："+hostIP+"主機名稱："+hostName+"\n"+"Port："+port+"\n";
					
				}  else {
					result = " 已存在 !!!\n"+"\n"+"系統ID："+bssId+"\n"+"子系統ID："+subSysId+"\n"+"主機IP："+hostIP+"\n"+"Port："+port+"\n";		
				}
			}
		} catch (SQLException e) {
			result = "異動"+hostIP+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("SQLException")+errPars, wid.isPrint2Console );
		} catch (UnsupportedEncodingException e) {
			result = "異動"+hostIP+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("UnsupportedEncodingException")+errPars, wid.isPrint2Console );
		} catch (Exception e) {
			result = "異動"+hostIP+"失敗!!\n\n";
			result += wid.errProcess(e);
			wid.kem(conn, ps, e, wid.toEType("Exception")+errPars, wid.isPrint2Console );
		} finally {
			try {
				if (rs!= null) {rs.close();}
				if (ps!= null) {ps.close();}
				if (conn!= null) {conn.close();}
			} catch (SQLException e) {
				System.out.println(wid.errProcess(e));
			}			
		}
		
		response.getWriter().write(result);		
	}
	
	private boolean isDuplicated(String bssId,String subSysId,String hostIP,int port,Connection conn,PreparedStatement ps, ResultSet rs) throws SQLException {
		String strSQL = "SELECT COUNT(*) FROM hosts WHERE ip=? AND subsysid=? AND bssid=? AND port=?";
		
		ps = conn.prepareStatement(strSQL);
		ps.setString(1, hostIP);
		ps.setString(2, subSysId);
		ps.setString(3, bssId);
		ps.setInt(4, port);
		rs = ps.executeQuery();
		rs.next();

		return rs.getInt(1) == 0?false:true;
	}
}